﻿
using UnityEngine.Networking;
using UnityEngine;

public class PlayerController : NetworkBehaviour
{
    public GameObject bulletPrefab;
    public Transform bulletSpawn;
    private Vector3 lastPos;
    void Update()
    {
        if (!isLocalPlayer)
        {
            return;
        }
        var x = Input.GetAxis("Horizontal") * Time.deltaTime * 3.0f;
        var z = Input.GetAxis("Vertical") * Time.deltaTime * 3.0f;

        if (x != 0 || z != 0)
        {
            transform.Translate(x, 0, z, Space.World);
            Vector3 movement = transform.position - lastPos;
            Quaternion endRotate = Quaternion.LookRotation(movement);
            transform.rotation = Quaternion.Lerp(transform.rotation, endRotate, 5.0f * Time.deltaTime);
            lastPos = transform.position;
        }

        if (Input.GetKeyDown(KeyCode.Space))
        {
            CmdFire();
        }
    }

    [Command]
    void CmdFire()
    {
        // Create the Bullet from the Bullet Prefab
        var bullet = (GameObject)Instantiate(
            bulletPrefab,
            bulletSpawn.position,
            bulletSpawn.rotation);

        // Add velocity to the bullet
        bullet.GetComponent<Rigidbody>().velocity = bullet.transform.forward * 12;

        NetworkServer.Spawn(bullet);

        // Destroy the bullet after 2 seconds
        Destroy(bullet, 2.0f);
    }


    public override void OnStartLocalPlayer()
    {
        transform.GetComponent<MeshRenderer>().material.color = Color.blue;
        // tag = "Player";
    }
}
